/*
 * File:   ConsoleLoggerTest.cpp
 * Author: Daniela
 *
 * Created on Mar 23, 2013, 11:04:22 PM
 */

#include "ConsoleLoggerTest.h"
#include "../../src/log/ConsoleLogger.h"
#include <stdlib.h>
#include <string.h>


CPPUNIT_TEST_SUITE_REGISTRATION(ConsoleLoggerTest);

ConsoleLoggerTest::ConsoleLoggerTest() {
}

ConsoleLoggerTest::~ConsoleLoggerTest() {
}

void ConsoleLoggerTest::setUp() {
}

void ConsoleLoggerTest::tearDown() {
}

void ConsoleLoggerTest::testLog() {
    ConsoleLogger* consoleLogger = new ConsoleLogger();
    LoggingLevel level = INFO;
    const char* source = __PRETTY_FUNCTION__;
    unsigned int threadID = (unsigned int) pthread_self();
    char* msgToLog = "Hello World";

    int pipes[2];
    int savedStdout;

    savedStdout = dup(STDOUT_FILENO); /* save stdout for display later */

    if (pipe(pipes) != 0) { /* make a pipe */
        exit(1);
    }

    dup2(pipes[1], STDOUT_FILENO); /* redirect stdout to the pipe */
    close(pipes[1]);
    
    consoleLogger->log(level, threadID, source, msgToLog);
    
    int size = 200;
    char* consoleBuffer = (char*) malloc(sizeof (char) * size);
    read(pipes[0], consoleBuffer, size); /* read from pipe into buffer */
    dup2(savedStdout, STDOUT_FILENO); /* reconnect stdout for testing */
    
    char* loggingLevelTest = strstr(consoleBuffer, "INFO");
    char* messageForTest = strstr(consoleBuffer, msgToLog);
    CPPUNIT_ASSERT(loggingLevelTest != 0);
    CPPUNIT_ASSERT(messageForTest != 0);
}
